import {BaseApi} from "./BaseApi.ts";
import type {NgaResponse} from "../types/NgaResponse.ts";
import {buildTopicDetailData, buildTopicDetailDataRaw, type TopicDetailDataRaw} from "../types/TopicDetail.ts";
import {parseLocation} from "../types/NgaLocation.ts";

export class TopicReadApi extends BaseApi {

    readTopic = (tid: number, page?: number | 'e' | undefined, authorId?: number | undefined) => this.read({
        tid,
        page,
        authorid: authorId
    })
    readTopicHtml = (tid: number, page?: number | 'e' | undefined, authorId?: number | undefined) => this.readHtml({
        tid,
        page,
        authorid: authorId
    })
    /**
     * 只读匿名
     */
    readAnonymous = (tid: number, pid: number, page?: number | 'e' | undefined) => this.read({tid, pid, page, opt: 512})

    readReply = (pid: number) => this.read({pid})
    // 获取单个回复的跳转位置，需配合nginx配置
    toReply = (pid: number) => this.instance.get<{ redirect: boolean, location: string }>("read.php", {params: {pid, to: 1, __output: 11}})
        .then(res => parseLocation(res.data.location))
    readReplyHtml = (pid: number) => this.readHtml({pid})
    // 赞踩
    recommend = (value: 1 | -1, tid: number, pid?: number) => this.postNuke({
        tid, pid, value,
        __act: "add",
        __lib: "topic_recommend",
    })
    /**
     * 投票或菠菜
     * @param tid
     * @param data 投票时填写项目ID，菠菜时填写 [项目ID, 金额]
     */
    vote = (tid: number, data: number[]) => this.postNuke({
        __act: "vote",
        __lib: "vote",
        tid, voteid: data.map(String).join(',')
    })
    /**
     * 举报
     * @param tid 主题ID
     * @param pid 回复ID
     * @param reason 理由
     */
    report = (tid: number, pid?: number | undefined, reason?: string | undefined) => this.postNuke({
        __act: "report",
        __lib: "log_post",
        tid,
        pid,
        info: reason,
    })


    /**
     * 通用请求
     * @param params 参数
     */
    read = (params: any) => this.instance.get<NgaResponse<TopicDetailDataRaw>>("read.php", {
        params: {
            ...params,
            __output: 11
        }
    })
        .then(async (res) => {
            // 请求错误，转向html
            if (typeof res.data === 'string') {
                return await this.readHtml(params)
            }
            return buildTopicDetailData((res.data.data))
        })
    readHtml = (params: any) => this.instance.get<string>("read.php", {params: {...params}}).then(res => {
        const raw = buildTopicDetailDataRaw(res.data)
        return buildTopicDetailData(raw)
    })

    postNuke = (params: any) => this.instance.post("nuke.php", undefined, {params: {...params, __output: 11,}})
        .then(res => res.data.data)
}